package com.service;

import com.domain.BlogArticle;
import com.domain.Statistic;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.BlogArticleMapper;
import com.mapper.CommentMapper;
import com.mapper.StatisticMapper;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ArticleService {
    @Autowired
    BlogArticleMapper blogArticleMapper;
    @Autowired
    StatisticMapper statisticMapper;
    @Autowired
    CommentMapper commentMapper;

    public List<BlogArticle> getHeatArticles( ) {
        List<Statistic> list = statisticMapper.getStatistic();
        List<BlogArticle> articleList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            BlogArticle article = blogArticleMapper.selectArticleWithId(list.get(i).getArticleId());
            article.setHits(list.get(i).getHits());
            article.setCommentsNum(list.get(i).getCommentsNum());
            articleList.add(article);
            if(i>=9){
                break;
            }
        }
        return articleList;

    }
   public PageInfo<BlogArticle> selectArticleWithPage(Integer page,Integer count){
       PageHelper.startPage(page,count);
       List<BlogArticle> articleList = blogArticleMapper.selectArticleWithPage();

       for(int i = 0; i<articleList.size(); i++){
           BlogArticle article = articleList.get(i);
           Statistic statistic = statisticMapper.selectStatisticArticleWithId(article.getId());
           article.setHits(statistic.getHits());
           article.setCommentsNum(statistic.getCommentsNum());
       }
       PageInfo<BlogArticle> pageInfo = new PageInfo<>(articleList);
       return pageInfo;
   }
   public void publish(BlogArticle article){
        article.setContent(EmojiParser.parseToAliases(article.getContent()));
        article.setCreated(new Date());
        article.setHits(0);
        article.setCommentsNum(0);
        blogArticleMapper.publishArticle(article);
        statisticMapper.addStatistic(article);
   }
}
